module.exports = class extends koahub.controller {

    async _initialize() {


        if (!this.isLogin()) {
            this.redirect('/admin/public/login');
        }


        // console.log(koahub.controllers);
        // console.log(koahub.services);

        this.state.theme = '';
        // this.state.adminUsername = this.session.adminUsername;

        if (this.session.adminId) {
            //系统管理员必须具备基本的系统管理权限
            const {code, message} = await this.checkAccessPermission('manage_system', '用户不能维护系统后台', true);

            //访问Service的实例
            let service = this.service('admin/administrator', this.session.adminId);
            // const Administrator = this.model('admin/Administrator');
            // const admin = await Administrator.findById(this.session.adminId).exec();
            const admin = service.getUserInfo();

            if (admin) {
                admin.password = undefined;

                this.state.user = admin;
                if (this.isPjax()) {
                    this.state.layout = false;
                } else {
                    this.state.layout = '/admin/layout';

                    const MenuModel = this.model('admin/Menu');
                    const groups = await MenuModel.getMenuGroups();
                    // const items = await MenuModel.getMenuByGroup('系统');
                    this.state.layoutData = {};
                    let menu = [];
                    for (let group of groups) {
                        let item = {
                            group: group,
                            items: await MenuModel.getMenuByGroup(group)
                        };
                        menu.push(item);
                    }
                    this.state.layoutData.menu = menu;
                }
            } else {
                this.error('/admin/public/login');
            }
        } else {
            this.error('/admin/public/login');
        }
    }

    async checkAccessPermission(code, errmsg, forceLogin = false) {
        let allowed = await this.rbac.checkByCode(this.session.adminId, code, 'admin');
        if (!allowed && forceLogin) {
            this.forceLogin(errmsg);
        } else {
            return {code: allowed, message: errmsg};
        }
    }

    forceLogin(msg) {
        // this.redirect('/admin/public/login?err=' + encodeURI(msg));
        if (typeof msg === 'string') {
            this.redirect('/admin/public/login?err=' + encodeURI(msg));
        } else {
            this.redirect('/admin/public/login');
        }
    }

    async changeModelField(model, id, field, value) {
        const Model = this.model(model);
        let update = {};
        update[field] = value;
        await Model.findByIdAndUpdate(id, update).exec();
    }

    isLogin() {
        if (this.session.adminId) {
            return true;
        } else {
            return false;
        }
    }
};
